package cn.witsky.rtp2ws.client.ws;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.witsky.rtp2ws.domain.Rtp;
import net.sf.json.JSONObject;

public   class  ClientListener {
	private static Logger logger = LoggerFactory.getLogger(ClientListener.class);
	public int byteVersion;	
	public Rtp rtp=null;	
	private String taskId="";
	public ClientListener(Rtp rtp) {
		this.rtp=rtp;
		taskId=this.rtp.getRtpId();
	}
	
	public int getByteVersion() {
		return byteVersion;
	}
	public void setByteVersion(int byteVersion) {
		this.byteVersion = byteVersion;
	}
	public  void  onMessage(JSONObject jsonMsg) {
		Client client=rtp.getClient();
		if(client==null) {
			logger.info("task:{}又触发了.........",this.rtp.getRtpId());
			return ;
		}
		logger.info("task:{} receiveMsg:{}",this.rtp.getRtpId(),jsonMsg);
		int status = jsonMsg.optInt("status",0);
		if (rtp.getRetry().getCount() > 0) {
			if (status == 0) {				
				int bytesLen = jsonMsg.optInt("receive-byte",0);
				boolean suc = rtp.getRetry().setReciveByte(bytesLen,this.getByteVersion());
				if (suc) {
					logger.info("wsClient:{}修改成功了.......", taskId);
				} else {
					logger.warn("wsClient:{}已经超时了，recive-byte被其他线程已经修改了.......", taskId);
				}
				rtp.wakeUpTask();
			}else {
				logger.warn("wsClient:{}收到异常状态:{}",taskId,status);
			}
		}else {
			if(status>0) {
				logger.warn("wsClient:{}第一次收到异常状态:{}",taskId,status);
			}else {
				logger.info("wsClient:{}第一次收到状态:{}",taskId,status);
			}
		}
	}
	public  void  onClose() {
		logger.warn("wsClient:{}连接被关闭了......", taskId);
		this.getRtp().clearWsClient();
	}
	public  void  onError() {
		logger.error("wsClient:{}程序出现异常了......", taskId);
	}
	public Rtp getRtp() {
		return rtp;
	}
	
}
